import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h, toRaw } from "vue";
import { deviceDetection } from "@pureadmin/utils";
import {
  getConsumptionRecords,
  createConsumptionRecord,
  updateConsumptionRecord,
  deleteConsumptionRecord
} from "@/api/ads";
import type {
  ConsumptionRecordItem,
  UserOption,
  AgentOption,
  AccountOption
} from "./types";

// 直接导入组件
import BatchForm from "../batch-form.vue";
import EditForm from "../form.vue";

export function useAdConsumption() {
  const form = reactive({
    user_id: "",
    agent_id: "",
    ad_plan_id: "", // 广告计划筛选，空字符串表示全部
    // start_date: "",
    // end_date: "",
    consumption_date:[],
    keyword: ""
  });

  const formRef = ref();
  const batchFormRef = ref();
  const dataList = ref<ConsumptionRecordItem[]>([]);
  const loading = ref(true);
  const userOptions = ref<UserOption[]>([]);
  const agentOptions = ref<AgentOption[]>([]);
  const accountOptions = ref<AccountOption[]>([]);
  const adPlanOptions = ref([
    { value: "0", label: "计划1" },
    { value: "1", label: "计划2" }
  ]);
  const currentUserId = ref<number | null>(null);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "记录ID",
      prop: "id",
      width: 80,
      align: "center"
    },
    {
      label: "投放人员",
      prop: "user",
      width: 120,
      showOverflowTooltip: true,
      formatter: ({ user }) => user?.username || "-"
    },
    {
      label: "消耗日期",
      prop: "consumption_date",
      width: 120,
      align: "center"
    },
    {
      label: "代理商",
      prop: "agent",
      minWidth: 150,
      showOverflowTooltip: true,
      cellRenderer: ({ row }) => {
        const agent = row.agent;
        if (!agent) return "-";
        // 优先使用后端返回的platform_text，如果没有则使用转换函数
        const platformText = agent.platform_text || getPlatformText(agent.platform);
        return (
          <div>
            <div>{agent.name}</div>
            <div style="color: #999; font-size: 12px;">{platformText}</div>
          </div>
        );
      }
    },
    {
      label: "消耗金额",
      prop: "total_amount",
      width: 120,
      align: "right",
      cellRenderer: ({ row }) => (
        <div style="display: flex; flex-direction: column; align-items: flex-end;">
          <span style="color: #f56c6c; font-weight: bold;">
            {formatAmount(row.total_amount || 0)}
          </span>
          {row.ad_plan_id !== 0 && (
            <el-tag
              size="small"
              type="warning"
              style="margin-top: 2px; font-size: 10px;"
            >
              计划2
            </el-tag>
          )}
        </div>
      )
    },
    {
      label: "账号消耗明细",
      prop: "details",
      minWidth: 200,
      showOverflowTooltip: true,
      cellRenderer: ({ row }) => {
        const details = row.details || [];
        if (details.length === 0) {
          return <span style="color: #999;">-</span>;
        }
        return (
          <div>
            {details.slice(0, 3).map((detail, index) => (
              <div key={index} style="margin-bottom: 2px;">
                <span>{detail.account?.account_no || "-"}</span>
                <span style="color: #999; margin-left: 8px;">
                  {formatAmount(detail.amount || 0)}
                </span>
              </div>
            ))}
            {details.length > 3 && (
              <div style="color: #999; font-size: 12px;">
                还有 {details.length - 3} 个账号...
              </div>
            )}
          </div>
        );
      }
    },
    {
      label: "创建时间",
      prop: "created_at",
      width: 160,
      formatter: ({ created_at }) => formatTime(created_at || 0)
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  /** 格式化金额显示 */
  function formatAmount(amount: number | string): string {
    const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
    if (isNaN(numAmount)) return '$0.00';
    return `${numAmount.toFixed(2)}`;
  }

  /** 格式化时间显示 */
  function formatTime(input: number | string | null | undefined): string {
    if (!input || input === 0 || input === "0") return "-";

    let date: Date;

    if (typeof input === 'string') {
      if (input.includes('-') && (input.includes(':') || input.includes(' '))) {
        date = new Date(input);
      } else {
        const numTimestamp = parseFloat(input);
        if (isNaN(numTimestamp) || numTimestamp <= 0) return "-";

        if (numTimestamp.toString().length === 10) {
          date = new Date(numTimestamp * 1000);
        } else {
          date = new Date(numTimestamp);
        }
      }
    } else {
      const numTimestamp = Number(input);
      if (isNaN(numTimestamp) || numTimestamp <= 0) return "-";

      const timestampStr = numTimestamp.toString();
      if (timestampStr.length === 10) {
        date = new Date(numTimestamp * 1000);
      } else if (timestampStr.length === 13) {
        date = new Date(numTimestamp);
      } else {
        if (numTimestamp > 1000000000000) {
          date = new Date(numTimestamp);
        } else {
          date = new Date(numTimestamp * 1000);
        }
      }
    }

    if (isNaN(date.getTime())) return "-";

    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit"
    });
  }

  /** 获取平台文本 */
  function getPlatformText(platform: number | string): string {
    const platformMap = {
      1: 'TikTok',
      2: 'Facebook',
      'tiktok': 'TikTok',
      'facebook': 'Facebook',
      'google': 'Google',
      'meta': 'Meta'
    };
    // 处理字符串数字
    const key = typeof platform === 'string' && /^\d+$/.test(platform)
      ? parseInt(platform)
      : platform;
    return platformMap[key] || platform || '-';
  }

  /** 获取消耗记录列表 */
  function getTableList() {
    loading.value = true;
    const params = {
      limit: pagination.pageSize,
      page: pagination.currentPage,
      ...toRaw(form)
    };

    getConsumptionRecords(params)
      .then(({ data }) => {
        dataList.value = data.data || [];
        pagination.total = data.total || 0;

        // 更新选项数据
        userOptions.value = data.user_options || [];
        agentOptions.value = data.agent_options || [];
        accountOptions.value = data.account_options || [];

        // 记录当前用户ID，用于新增时默认选中
        if (data.current_user_id) {
          currentUserId.value = data.current_user_id;
        }
      })
      .catch(() => {
        dataList.value = [];
        pagination.total = 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  /** 搜索 */
  function onSearch() {
    pagination.currentPage = 1;
    getTableList();
  }

  /** 重置搜索表单 */
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  /** 分页大小变化 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    getTableList();
  }

  /** 当前页变化 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    getTableList();
  }

  /** 打开新增对话框 */
  function openDialog() {
    // 确保数据已加载
    if (userOptions.value.length === 0 || agentOptions.value.length === 0) {
      console.log("数据未加载完成，正在重新获取...");
      getTableList();
      // 等待数据加载完成后再打开弹窗
      setTimeout(() => {
        if (userOptions.value.length === 0 || agentOptions.value.length === 0) {
          message("数据加载失败，请稍后重试", { type: "error" });
          return;
        }
        openDialogCore();
      }, 1000);
    } else {
      openDialogCore();
    }
  }

  /** 打开弹窗核心逻辑 */
  function openDialogCore() {
    console.log("准备打开弹窗，数据情况：", {
      userOptions: userOptions.value.length,
      agentOptions: agentOptions.value.length,
      accountOptions: accountOptions.value.length
    });

    addDialog({
      title: "新增消耗记录",
      props: {
        userOptions: userOptions.value,
        agentOptions: agentOptions.value,
        accountOptions: accountOptions.value
      },
      width: "55%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(BatchForm, {
        ref: batchFormRef,
        formInline: {
          user_id: currentUserId.value?.toString() || "",
          consumption_date: "",
          ad_plan_id: 0,
          input_type: "manual",
          manual_data: [],
          account_data: []
        },
        userOptions: userOptions.value,
        agentOptions: agentOptions.value,
        accountOptions: accountOptions.value
      }),
      beforeSure: (done, { options }) => {
        const FormRef = batchFormRef.value.getRef();
        const curData = options.props || {};

        function chores() {
          done(); // 关闭弹框
          getTableList(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            // 清除之前的错误
            batchFormRef.value.clearError();
            batchFormRef.value.setLoading(true);

            // 提交表单数据
            const formData = batchFormRef.value.getFormData();
            createConsumptionRecord(formData)
              .then((response) => {
                console.log('创建响应:', response);
                // 检查业务逻辑是否成功
                if (response.success === false || response.code !== 0) {
                  throw new Error(response.message || '创建失败');
                }
                message("创建成功", { type: "success" });
                chores();
              })
              .catch((error) => {
                console.error('创建请求失败:', error);
                // 在表单中显示错误信息
                const errorMessage = error.message || error.response?.data?.message || '创建失败，请稍后重试';
                console.log('设置错误信息:', errorMessage);
                batchFormRef.value.setError(errorMessage);
                // 不调用done()，保持弹窗开启
              })
              .finally(() => {
                batchFormRef.value.setLoading(false);
              });
          }
        });
      }
    });
  }

  /** 编辑记录 */
  function editRecord(row: ConsumptionRecordItem) {
    // 检查是否有明细数据
    const hasDetails = row.details && row.details.length > 0;

    if (hasDetails) {
      // 有明细数据，使用批量编辑表单
      editRecordWithDetails(row);
    } else {
      // 没有明细数据，使用简单编辑表单
      editRecordSimple(row);
    }
  }

  /** 编辑有明细数据的记录 */
  function editRecordWithDetails(row: ConsumptionRecordItem) {
    // 将明细数据转换为账号录入格式
    const accountData = row.details?.map((detail, index) => ({
      key: `account_${Date.now()}_${index}`,
      account_id: detail.account_id.toString(), // 转换为字符串以匹配类型
      amount: detail.amount.toString()
    })) || [];

    addDialog({
      title: `编辑消耗记录 - ${row.id}`,
      props: {
        editMode: true,
        editId: row.id,
        userOptions: userOptions.value,
        agentOptions: agentOptions.value,
        accountOptions: accountOptions.value
      },
      width: "55%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(BatchForm, {
        ref: batchFormRef,
        formInline: {
          user_id: row.user_id || "",
          consumption_date: row.consumption_date || "",
          ad_plan_id: Number(row.ad_plan_id) || 0,
          input_type: 'account',
          manual_data: [],
          account_data: accountData
        },
        editMode: true,
        editData: {
          user_id: row.user_id,
          consumption_date: row.consumption_date,
          ad_plan_id: Number(row.ad_plan_id) || 0,
          input_type: 'account',
          account_data: accountData
        },
        userOptions: userOptions.value,
        agentOptions: agentOptions.value,
        accountOptions: accountOptions.value
      }),
      beforeSure: (done, { options }) => {
        const FormRef = batchFormRef.value.getRef();

        function chores() {
          done(); // 关闭弹框
          getTableList(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            // 清除之前的错误
            batchFormRef.value.clearError();
            batchFormRef.value.setLoading(true);

            // 获取表单数据
            const formData = batchFormRef.value.getFormData();
            // 添加编辑ID
            formData.edit_id = row.id;
            // 使用创建接口（后端会自动处理更新逻辑）
            createConsumptionRecord(formData)
              .then((response) => {
                console.log('编辑响应:', response);
                // 检查业务逻辑是否成功
                if (response.success === false || response.code !== 0) {
                  throw new Error(response.message || '更新失败');
                }
                message("更新成功", { type: "success" });
                chores();
              })
              .catch((error) => {
                console.error('编辑请求失败:', error);
                // 在表单中显示错误信息
                const errorMessage = error.message || error.response?.data?.message || '更新失败，请稍后重试';
                console.log('设置错误信息:', errorMessage);
                batchFormRef.value.setError(errorMessage);
                // 不调用done()，保持弹窗开启
              })
              .finally(() => {
                batchFormRef.value.setLoading(false);
              });
          }
        });
      }
    });
  }

  /** 编辑简单记录（无明细数据） */
  function editRecordSimple(row: ConsumptionRecordItem) {
    addDialog({
      title: `编辑消耗记录 - ${row.id}`,
      props: {
        formInline: {
          user_id: row.user_id,
          consumption_date: row.consumption_date,
          ad_plan_id: Number(row.ad_plan_id) || 0,
          agent_id: row.agent_id,
          total_amount: row.total_amount
        },
        userOptions: userOptions.value,
        agentOptions: agentOptions.value
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(EditForm, {
        ref: formRef,
        formInline: {
          user_id: row.user_id,
          consumption_date: row.consumption_date,
          ad_plan_id: Number(row.ad_plan_id) || 0,
          agent_id: row.agent_id,
          total_amount: row.total_amount
        },
        userOptions: userOptions.value,
        agentOptions: agentOptions.value
      }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as ConsumptionRecordItem;

        function chores() {
          done(); // 关闭弹框
          getTableList(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            // 清除之前的错误
            formRef.value.clearError();
            formRef.value.setLoading(true);

            updateConsumptionRecord(row.id, curData)
              .then((response) => {
                console.log('简单编辑响应:', response);
                // 检查业务逻辑是否成功
                if (response.success === false || response.code !== 0) {
                  throw new Error(response.message || '更新失败');
                }
                message("更新成功", { type: "success" });
                chores();
              })
              .catch((error) => {
                console.error('简单编辑请求失败:', error);
                // 在表单中显示错误信息
                const errorMessage = error.message || error.response?.data?.message || '更新失败，请稍后重试';
                console.log('设置错误信息:', errorMessage);
                formRef.value.setError(errorMessage);
                // 不调用done()，保持弹窗开启
              })
              .finally(() => {
                formRef.value.setLoading(false);
              });
          }
        });
      }
    });
  }

  /** 删除记录 */
  function deleteRecord(row: ConsumptionRecordItem) {
    deleteConsumptionRecord(row.id)
      .then((response) => {
        console.log('删除响应:', response);
        // 检查业务逻辑是否成功
        if (response.success === false || response.code !== 0) {
          throw new Error(response.message || '删除失败');
        }
        message("删除成功", { type: "success" });
        getTableList();
      })
      .catch((error) => {
        console.error('删除请求失败:', error);
        const errorMessage = error.message || error.response?.data?.message || '删除失败，请稍后重试';
        message(`删除失败: ${errorMessage}`, { type: "error" });
      });
  }

  /** 初始化 */
  onMounted(() => {
    getTableList();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    userOptions,
    agentOptions,
    accountOptions,
    adPlanOptions,
    currentUserId,
    onSearch,
    resetForm,
    getTableList,
    openDialog,
    openDialogCore,
    editRecord,
    deleteRecord,
    handleSizeChange,
    handleCurrentChange
  };
}
